import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/8 15:29
 * @description
 */
public class Solution {
    public static void main(String[] args) {

    }
    public String smallestSubsequence(String s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            cnt[c -'a']++;
        }
        // 是否访问过
        boolean[] visited = new boolean[26];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (!visited[ch - 'a']) {
                while (sb.length() > 0 && sb.charAt(sb.length() - 1) > ch) {
                    if (cnt[sb.charAt(sb.length() - 1) -'a'] > 0) {
                        visited[sb.charAt(sb.length() - 1) - 'a'] = false;
                        sb.deleteCharAt(sb.length() - 1);
                    }else {
                        break;
                    }
                }
                visited[ch - 'a'] = true;
                sb.append(ch);
            }
            cnt[ch - 'a'] -= 1;
        }
        return sb.toString();
    }
}
